package com.besall.allbase.view.activity.chipstoollevel4.protocol.Settings.storagemanager;

import static com.bes.bessdk.BesSdkConstants.BES_CONNECT_ERROR;
import static com.besall.allbase.bluetooth.service.Protocol.ProtocolConstants.GET_DEVICE_MEMORY_USED;
import static com.besall.allbase.common.utils.ActivityUtils.showToast;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import bb.lanxing.R;
import bb.lanxing.device.sgdevcie.storage.fragment.BBWorkoutsManagerFragment;
import bb.lanxing.devicelist.XZDeviceListActivity;
import bb.lanxing.fragment.base.BaseFragment;
import com.bes.bessdk.service.base.BesServiceListener;
import com.bes.sdk.device.HmDevice;
import com.bes.sdk.utils.SettingsJsonUtils;
import com.besall.allbase.bluetooth.service.Protocol.ProtocolConstants;
import com.besall.allbase.view.activity.chipstoollevel4.protocol.ProtocolPresenter;

public class StorageManagerFragment extends BaseFragment implements View.OnClickListener, BesServiceListener {
	TextView deviceName;
	TextView memoryUsage;
	LinearLayout workoutLL;
	LinearLayout rootBookLL;
	ProgressBar progressBar;
	private boolean hasInit = false;
	private View rootView;

	public static StorageManagerFragment newInstance() {
		return new StorageManagerFragment();
	}

	@Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		if (!hasInit) {
			View view = inflater.inflate(R.layout.fragment_device_storage_manager, container, false);
			bindView(view);
			hasInit = true;
			rootView = view;
		}
		return rootView;
	}

	private void bindView(View view) {
		String device_model = SettingsJsonUtils.getDeviceModel(requireContext());
		deviceName = view.findViewById(R.id.device_name);
		deviceName.setText(device_model);
		workoutLL = view.findViewById(R.id.ll_workout);
		workoutLL.setOnClickListener(this);
		rootBookLL = view.findViewById(R.id.ll_routeBook);
		rootBookLL.setOnClickListener(this);

		memoryUsage = view.findViewById(R.id.memory_usage);
		progressBar = view.findViewById(R.id.pgb);

		//startProgress();
	}

	@Override public void onClick(View v) {
		int id = v.getId();
		if (id == R.id.ll_workout) {
			getParentFragmentManager().beginTransaction().addToBackStack("StorageManagerFragment").replace(R.id.container, new BBWorkoutsManagerFragment()).commit();
		} else if (id == R.id.ll_routeBook) {
			getParentFragmentManager().beginTransaction().addToBackStack("StorageManagerFragment").replace(R.id.container, LaxingRouteBookManagerFragment.newInstance()).commit();
		}
	}

	@Override public void onTotaConnectState(boolean state, HmDevice hmDevice) {

	}

	@Override public void onErrorMessage(int msg, HmDevice hmDevice) {

	}

	@Override public void onStateChangedMessage(int msg, String msgStr, HmDevice hmDevice) {
		if (msg == BES_CONNECT_ERROR) {
			runOnUIThread(() -> showToast(msgStr));
			if (isAdded()) {
				Intent intent = new Intent(requireActivity(), XZDeviceListActivity.class);
				startActivity(intent);
			}
		} else if (msg == GET_DEVICE_MEMORY_USED) {
			String[] memory = msgStr.split(",");
			if (memory.length != 2) {
				throw new RuntimeException("get Memory error!");
			}
			runOnUIThread(() -> {
				memoryUsage.setText(String.format("%sM %s/%s %sM", memory[0], getString(R.string.setting_memory_used), getString(R.string.setting_memory_total), memory[1]));
				int used = Integer.parseInt(memory[0]);
				int total = Integer.parseInt(memory[1]);
				progressBar.setMax(total);
				progressBar.setProgress(used);
			});
		}
	}

	@Override public void onSuccessMessage(int msg, HmDevice hmDevice) {

	}

	@Override public void onResume() {
		super.onResume();
		requireActivity().setTitle(R.string.st_manage_storage);
		ProtocolPresenter protocolPresenter = ProtocolPresenter.getInstance();
		protocolPresenter.setProtocolServiceListener(this);
		protocolPresenter.getBikeWatchDataFromBesClient(ProtocolConstants.BIKEWATCH_GET_EMMC_INFO, "", "");
	}

	private void startProgress() {
		new Thread(() -> {
			progressBar.setMax(200);
			for (int begin = 10, max = 200; begin <= max; begin += 10) {
				final int progress = begin;
				runOnUIThread(() -> {
					progressBar.setProgress(progress);
					memoryUsage.setText(String.format("%sM/%sM", progress, 200));
				});
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					throw new RuntimeException(e);
				}
			}
		}).start();
	}
}
